<?php include "../../inc/classes.inc" ?>
<?php include "../../inc/constants.inc" ?>
<?php session_start(); ?>
<?php
	if ( isset($_SESSION['players']) && isset($_SESSION['user']) ) {
        $players = $_SESSION['players'];
        $user = $_SESSION['user'];

        $connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);
	    mysql_select_db(DB_CATALOG);
	    
	    $query = "SELECT tournament_id from zt_tournament where isCurrent = 1";
        $result = mysql_query($query, $connect);
        $row = mysql_fetch_assoc($result);
        $currentTournament = $row['tournament_id'];

        $query = "SELECT COUNT(1) AS listIsPending FROM zt_player_list pl 
        	join zt_tournament t on t.tournament_id = pl.tournament_id
        	WHERE t.iscurrent = 1 and club_id = ".$user->club_id." 
        	AND date_approved IS NULL";
        $result = mysql_query($query, $connect);
        $row = mysql_fetch_assoc($result);
        $listIsPending = $row['listIsPending'];
        
        $result = mysql_query("SET AUTOCOMMIT=0", $connect);
  	    $result = mysql_query("BEGIN", $connect);

        if ($listIsPending < 1) {
            // insert
            $query = "INSERT INTO zt_player_list (tournament_id, club_id, date_added, date_approved, date_modified, user_id)
            	VALUES ($currentTournament, ".$user->club_id.",NOW(),NULL,NULL,".$user->user_id.")";
	        $result = mysql_query($query, $connect);
	        $query = "SELECT LAST_INSERT_ID() AS playerListId";
	        $result = mysql_query($query, $connect);
	        $row = mysql_fetch_assoc($result);
	        $playerListId = $row['playerListId'];
        } else if ($listIsPending == 1 && isset($_GET['player_list_id']) == true) {
            // update
            $playerListId = $_GET['player_list_id'];
            $query = "UPDATE zt_player_list SET date_added = NOW() WHERE player_list_id = ".$playerListId;
            $result = mysql_query($query, $connect);
            $query = "DELETE FROM zt_player WHERE player_list_id = ".$playerListId;
            $result = mysql_query($query, $connect);
        }

        $nrOfInsertedPlayers = 0;
        while ($player = current($players)) {
            if (!empty($player->player_key)) {
				// existing player
                $query = sprintf("SELECT matricule from playernew where matricule = %u", $player->player_key);
            	$result = mysql_query($query, $connect);
	            $row = mysql_fetch_assoc($result);
	            
	            $playerId = $row['matricule'];
	            $indexNr = key($players);
	
	            if (!empty($player->team_name)) {
	                $query = sprintf("SELECT team_id from zt_team where team_nr = %d and club_id = %u and tournament_id = %u",
	                    $player->team_name, $user->club_id, $currentTournament);
	                $result = mysql_query($query, $connect);
	                $row = mysql_fetch_assoc($result);
	                $teamId = $row['team_id'];
	
	                $query = sprintf("INSERT INTO zt_player(player_key, player_list_id, team_id, index_nr) VALUES (%u, %u, %u, %u)",
	                    $playerId, $playerListId, $teamId, $indexNr+1);
	
	                if ($result = mysql_query($query, $connect)) {
	                    if (mysql_affected_rows($connect) == 1) {
	                        $nrOfInsertedPlayers = $nrOfInsertedPlayers + 1;
	                    }
	                } else {
	                    echo $query." ; ".mysql_error()."<br>";
	                }
	
	            } else {
	                $query = sprintf("INSERT INTO zt_player(player_key, player_list_id, index_nr) VALUES (%u, %u, %u)",
	                    $playerId, $playerListId, $indexNr+1);
	
	                if ($result = mysql_query($query, $connect)) {
	                    if (mysql_affected_rows($connect) == 1) {
	                        $nrOfInsertedPlayers = $nrOfInsertedPlayers + 1;
	                    }
	                } else {
	                    echo $query." ; ".mysql_error()."<br>";
	                }
	            }
	            
            } else {
            	$result = mysql_query("ROLLBACK", $connect);
                $msg = "Nieuwe speler '".$player->player_name."' niet opgeslagen. Contacteer de webmaster -> debug=[".$query."]";
    			redirect("/tornooien/zt-php/view_players_list.php?msg=".$msg);
            }            

            next($players);
        }

        if ($nrOfInsertedPlayers == count($players) ) {
            $result = mysql_query("COMMIT", $connect);
            unset($_SESSION['players']);
            $msg = "Spelerslijst is doorgestuurd naar ligatornooileider !";
            redirect("/tornooien/zt-php/view_players_list.php?msg=".$msg);
            /*$result = mysql_query("select clubname from club where club_id = ".$user->club_id);
            $row = mysql_fetch_assoc($result);
            $clubname = $row['clubname'];
            $msg="test";
            $body = chunk_split(base64_encode($msg)) . "\r\n";
            ini_set("SMTP", "smtp.schaakliga-antwerpen.info");
            ini_set("smtp_port", "587");
            ini_set("sendmail_from", "webmaster@schaakliga-antwerpen.info");
            mail('mordredqv@gmail.com','Spelerslijst ingediend door '.$clubname.' op '.date('d-m-Y H:i:s'),$body);*/
        } else {
            $result = mysql_query("ROLLBACK", $connect);
        }

    } else {
        $msg = "Ongeldige parameters voor validatie spelerslijst.";
    	redirect("/tornooien/zt-php/view_players_list.php?msg=".$msg);
    }
?>